<?php

namespace App\Module;

use App\depository\PermissionsDep;
use App\depository\RoleHasPermissionsDep;
use App\depository\RolesDep;
use App\depository\ManageMapDep;
use App\depository\SystemDep;
use App\Enum\CommonEnum;
use App\Enum\PermissionsEnum;
use App\Enum\RolesEnum;
use App\Enum\TeamsEnum;
use App\Service\DictService;
use App\depository\UserDep;

class MapModule extends BaseModule
{
    public function init($request)
    {

        $param = $request->input();

        $dictService = new DictService();
        $dictService->setUsers()->setTeamStatus();

        $systemDep = new SystemDep();
        $resSystem = $systemDep->first();

        $data = [
            'dict' => $dictService->getDict(),
            'map_json' => $resSystem->map_json
        ];

        return self::response($data);
    }


    public function add($request)
    {
        $param = $request->input();

        if (empty($param['map_name'])) {
            return self::response([], '请输入地图名称', 100);
        }

        $dep = new ManageMapDep();

        $data = [
            'map_name' => $param['map_name'],
            'zh_name' => $param['zh_name'],
        ];

        $dep->add($data);

        return self::response();
    }

    public function del($request)
    {
        $param = $request->input();

        $dep = new ManageMapDep();

        $dep->del($param['id']);
        return self::response();
    }

    public function edit($request)
    {
        $param = $request->input();

        if (empty($param['map_name'])) {
            return self::response([], '请输入地图名称', 100);
        }

        $dep = new ManageMapDep();
        $data = [
            'map_name' => $param['map_name'],
            'zh_name' => $param['zh_name'],
        ];

        $dep->upd($param['id'], $data);

        return self::response();
    }

    public function list($request)
    {
        $param = $request->input();

        $dep = new ManageMapDep();
        $userDep = new UserDep();
        $resList = $dep->list($param);

        $data['list'] = $resList->map(function ($item) use ($userDep) {
            $resUser = $userDep->firstById($item->leader_id);
            return [
                'id' => $item->id,
                'map_name' => $item->map_name,
                'zh_name' => $item->zh_name,
            ];
        });

        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];

        return self::response($data);
    }

    public function json($request)
    {
        $param = $request->input();

        $dep = new SystemDep();
        $resSystem = $dep->first();
        if (!$resSystem) {
            return self::response([], '请联系管理员添加系统配置',200);
        }

        $resSystem->map_json = $param['text'];
        $resSystem->save();

        return self::response([]);
    }
}

